<template>
  <div class="big-div" >
    <div class="left-div">

      <div id="main"  style="height: 742px;width: 1200px;margin-left: 0px"></div>
        <el-button @click="buyClick">买入</el-button>
        <el-button @click="sellClick">卖出</el-button>
      <el-button @click="timesharagClick">分时图</el-button>
    </div>
    <div class="right-div">
      <div class="small-div1">
        <br>
        <span v-for="(o,index) in sellData" class="item">
          {{o.name}}
          <span class="data-space"></span> <!-- 这里设置了一个间隔 -->
          {{o.sellPrice}}
            <span class="data-space"></span> <!-- 这里设置了一个间隔 -->
          {{o.hands}}
        <el-divider></el-divider>
        </span>
      </div>
      <br><br>
      <div class="small-div2">
        <hr>
          <span v-for="(o,index) in buyData" class="item">
          {{o.name}}
          <span class="data-space"></span> <!-- 这里设置了一个间隔 -->
          {{o.buyPrice}}
            <span class="data-space"></span> <!-- 这里设置了一个间隔 -->
          {{o.hands}}
        <el-divider></el-divider>
        </span>
      </div>
    </div>

  </div>
</template>
<script>
import * as echarts from 'echarts';
import {buyList, getSellList, getTimesharing, lineList} from "@/api/stock/stock";
export default {
  name: "KIndex",
  data() {
    return {
      graphDataVos: [],
      buyData:[],
      sellData:[],
      wsUrl: 'ws://127.0.0.1:8080/test/one',
      // ws地址
      websock: null, // ws实例,
      timesharData:[]
    }
  },
  methods: {

    getList() {
      let symbol = this.$route.query.symbol;
      lineList(symbol).then(response => {
        this.graphDataVos = response.data;
        this.renderChart();
      });
    },
    initChart() {
      var chartDom = document.getElementById('main');
      this.myChart = this.$echarts.init(chartDom);
      this.myChart.setOption(this.option);
    },
    renderChart() {
      var chartDom = document.getElementById('main');
      var myChart = echarts.init(chartDom, null, {
        useDirtyRect: true
      });
      var option;

      const upColor = '#ec0000';
      const upBorderColor = '#8A0000';
      const downColor = '#00da3c';
      const downBorderColor = '#008F28';

      const processedData = this.processData(this.graphDataVos);

      function calculateMA(dayCount) {
        var result = [];
        for (var i = 0, len = processedData.values.length; i < len; i++) {
          if (i < dayCount) {
            result.push('-');
            continue;
          }
          var sum = 0;
          for (var j = 0; j < dayCount; j++) {
            sum += +processedData.values[i - j][1];
          }
          result.push(sum / dayCount);
        }
        return result;
      }
      let trade = this.$route.query.trade;
      option = {
        title: {
          text: '当前最新价'+trade,
          left: 60,
          color: '#d90f37',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30']
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: processedData.categoryData,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          min: 'dataMin',
          max: 'dataMax'
        },
        yAxis: {
          scale: true,
          splitArea: {
            show: true
          }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 50,
            end: 100
          },
          {
            show: true,
            type: 'slider',
            top: '90%',
            start: 50,
            end: 100
          }
        ],
        series: [
          {
            name: '日K',
            type: 'candlestick',
            data: processedData.values,
            itemStyle: {
              color: upColor,
              color0: downColor,
              borderColor: upBorderColor,
              borderColor0: downBorderColor
            }
          },
          {
            name: 'MA5',
            type: 'line',
            data: calculateMA(5),
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
          },
          {
            name: 'MA10',
            type: 'line',
            data: calculateMA(10),
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
          },
          {
            name: 'MA20',
            type: 'line',
            data: calculateMA(20),
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
          },
          {
            name: 'MA30',
            type: 'line',
            data: calculateMA(30),
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
          }
        ]
      };

      option && myChart.setOption(option);
    },


    processData(rawData) {
      const categoryData = [];
      const values = [];
      for (var i = 0; i < rawData.length; i++) {
        categoryData.push(rawData[i].day);
        values.push([rawData[i].open, rawData[i].close, rawData[i].low, rawData[i].high]);
      }
      return {
        categoryData: categoryData,
        values: values
      };
    },
    /*获取买入的列表*/
    // getBuyList(){
    //   let trade = this.$route.query.trade;
    //   let symbol = this.$route.query.symbol;
    //   buyList(symbol,trade).then(res=>{
    //     this.buyData = res.data;
    //   })
    // },/*获取卖出的列表*/
    // sellList(){
    //   let trade = this.$route.query.trade;
    //   let symbol = this.$route.query.symbol;
    //   getSellList(symbol,trade).then(res=>{
    //     this.sellData = res.data;
    //   })
    // },/*买入*/
    buyClick(){
      this.$router.push({path:"/stock/buy",query:{symbol:this.$route.query.symbol,trade:this.$route.query.trade,state:'1'}})
    },sellClick(){
      this.$router.push({path:"/stock/buy",query:{symbol:this.$route.query.symbol,trade:this.$route.query.trade,state:'2'}})
    },

    initWebSocket() {
      if (typeof WebSocket === 'undefined')
        return console.log('您的浏览器不支持websocket')
      this.websock = new WebSocket(this.wsUrl)

      //this.websock = new WebSocket('ws://127.0.0.1:8080/test/oneToOne')
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    websocketonopen() {
      let symbol = this.$route.query.symbol;
      let trade = this.$route.query.trade;
      // 连接建立之后执行send方法发送数据
      let actions = { symbol:symbol,trade:trade}
      this.websocketsend(JSON.stringify(actions))

    },
    websocketonerror() {
      // 连接建立失败重连
      this.initWebSocket()
    },
    websocketonmessage(e) {
      // 数据接收
      const redata = e.data
      let parse = JSON.parse(redata);
      console.log('接收的数据', parse.sysSell)//d
      this.sellData = parse.sysSell;
      console.log('接收的数据', "=============")//d
      console.log('接收的数据', parse.sysBuys)//d
      this.buyData = parse.sysBuys;
    },
    websocketsend(Data) {
      // 数据发送
      this.websock.send(Data)
    },
    websocketclose(e) {
      // 关闭
      console.log('断开连接', e)
    },timesharagClick(){
      this.$router.push({path:"/stock/fenshi",query:{symbol:this.$route.query.symbol,trade:this.$route.query.trade}})
    }
    /*
    * 买入列表 websocket协议
    * */
  }, created() {
    this.getList();
    //this.getBuyList();
    //this.sellList();
  }, destroyed() {
    // 离开路由之后断开websocket连接
    this.websock.close()
  },mounted() {
    this.initWebSocket();//初始化websocket
  }
}
</script>

<style scoped>
.big-div {
  display: flex;
  width: 1500px;
  height: 860px;
}
.aa{
  border: 1px solid black;
  flex: 1;
  width: 200px;
  height: 680px;
}


.left-div {
  flex: 1;
  width: 1130px;
  height: 350px;
}

.right-div {
  flex: 1;
  width: 800px;
  height: 340px;
}

.small-div1,
.small-div2 {
  width: 150px;
  height: 310px;
}
.data-item {
  display: flex;
  align-items: center;
}

.data-space {
  margin-right: 10px; /* 设置数据间的间距为 10px */
}
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 19px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}
</style>

